import org.junit.Test;

import java.sql.*;
import java.util.Properties;

/**
 * @author dinghao
 * @create 2021-09-18 17:08
 * @message
 */
public class DruidTest {
    @Test
    public void druidtest1(){
        // 配置broker上的地址
        String url = "jdbc:avatica:remote:url=http://localhost:8082/druid/v2/sql/avatica/";
        // 设置连接配置，或者使用空配置采用默认配置
        Properties connectionProperties = new Properties();
        //设置此连接的时区，这将影响时间函数和时间戳文字的行为。应该是像“America / Los_Angeles”等时区名称，也应该偏移“-08：00”。00
        connectionProperties.setProperty("sqlTimeZone", "Asia/Shanghai");
        String query = "SELECT * FROM druid.\"wikiticker-2015-09-12-sampled\"";

        try (Connection connection = DriverManager.getConnection(url, connectionProperties)) {
            try (
                    final Statement statement = connection.createStatement();
                    final ResultSet resultSet = statement.executeQuery(query)
            ) {
                while (resultSet.next()) {
                    String sb = parseResultSet(resultSet);
                    System.out.println(sb);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("=========动态配置查询参数============");
        try (Connection connection = DriverManager.getConnection(url, connectionProperties)) {
            PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) AS cnt FROM druid.\"wikiticker-2015-09-12-sampled\" WHERE user = ? OR namespace = ?");
            statement.setString(1, "GELongstreet");
            statement.setString(2, "Talk");
            final ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
//                String s = parseResultSet(resultSet);
//                System.out.println(s);
                System.out.println(resultSet.getInt("cnt"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回数据解析
     *
     * @param resultSet
     * @return
     * @throws SQLException
     */
    private static String parseResultSet(ResultSet resultSet) throws SQLException {
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < columnCount + 1; i++) {
            int columnType = metaData.getColumnType(i);
            switch (columnType) {
                case Types.TIMESTAMP:
                    Timestamp timestamp = resultSet.getTimestamp(i);
                    sb.append(timestamp).append(" ");
                    break;
                case Types.VARCHAR:
                    String string = resultSet.getString(i);
                    sb.append(string).append(" ");
                    break;
//                    其他类型自行实现
                default:
                    break;
            }
        }
        return sb.substring(0, sb.length() - 1);
    }
}
